<template>
  <div class="login-page mx-auto p-3 w-330">
    <h5 class="my-4 text-center">登录到专栏</h5>
      <validate-form @form-submit="onFormSubmit">
        <validate-input 
          type="text" 
          v-model="emailVal" 
          :rules="emailRules" 
          title="邮箱地址"/>
        <validate-input 
          type="password" 
          placeholder="请输入密码"
          v-model="passVal" 
          :rules="passRules" 
          title="密码"/>
          <template #submit>
            <button type="submit" class="btn btn-primary btn-block btn-large">登录</button>
          </template>
      </validate-form>
  </div>
</template>

<script lang="ts" setup>
import ValidateForm from '@/components/form/ValidateForm.vue';
import ValidateInput from '@/components/form/ValidateInput.vue';
import createMessage from '@/components/createMessage';
// import router from '@/router/router';  // 等价于 useRouter 实例化的内容
import { RulesProp } from '@/types';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';

const router = useRouter();
const store = useStore();

let emailVal = ref('');
let passVal = ref('');

const emailRules: RulesProp = [
  { type: 'required', message: '电子邮箱不能为空' },
  { type: 'email', message: '请输入正确的邮箱格式' }
]

const passRules: RulesProp = [
  { type: 'required', message: '密码不能为空' },
  { type: 'min', length: 6, message: '密码长度不能小于6个字符' },
  { type: 'max', length: 32, message: '密码长度不能长于32个字符'}
];

const onFormSubmit = (result: boolean) => {
  // console.log('validate result is => ' + result);
  if (result) {
    const payload = {
      email: emailVal.value,
      password: passVal.value
    }
    store.dispatch('loginAndFetch', payload).then(data => {
      // console.log(data);
      createMessage('登录成功， 2秒内跳转首页', 'success');
      setTimeout(() => {
        router.push("/");
      }, 2000);
    }).catch(e => {
      console.log(e)
    });
  }
}
</script>